﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;

namespace DapperExtensions
{
    public class OracleDynamicParameters : SqlMapper.IDynamicParameters
    {
        private DynamicParameters dynamicParameters = new DynamicParameters();
        private List<OracleParameter> oracleParameters = new List<OracleParameter>();

        public void Add(string name, object value = null, DbType? dbType = null, ParameterDirection? direction = null, int? size = null)
        {
            dynamicParameters.Add(name, value, dbType, direction, size);
        }

        public void Add(string name, OracleType oracleDbType, ParameterDirection direction)
        {
            var oracleParameter = new OracleParameter
            {
                ParameterName = name,
                OracleType = oracleDbType,
                Direction = direction
            };
            oracleParameters.Add(oracleParameter);
        }

        public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
        {
            ((SqlMapper.IDynamicParameters)dynamicParameters).AddParameters(command, identity);
            var oracleCommand = command as OracleCommand;
            if(oracleCommand != null)
            {
                oracleCommand.Parameters.AddRange(oracleParameters.ToArray());
            }
        }

        public static object GetOracleString(string source)
        {
            if(string.IsNullOrEmpty(source))
                return DBNull.Value;
            else
                return source;
        }

        public T Get<T>(string name)
        {
            return dynamicParameters.Get<T>(name);
        }
    }
}